package pos.data;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

import pos.domain.*;

public class JDBCInstallDAO implements IInstallDAO {

	private Connection conn;
	// private Statement stmt = null;

	public final static char QUERY_ENDS = ';';

	public JDBCInstallDAO() {
		conn = ConnectionManager.getInstance().checkOut();
		System.out.println("Se ha creado la conexi�n");
	}

	public void ejecScript(String archivo) {

		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(archivo));

			String line;

			StringBuffer query = new StringBuffer();
			boolean queryEnds = false;
			Statement stmt = null;
			try {
				stmt = (Statement) conn.createStatement();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while ((line = reader.readLine()) != null) {
				if (isComment(line) || line.length() > 0
						&& (line.charAt(0) == '/' || line.charAt(0) == '-')
						|| line.length() == 0)
					continue;
				try {
					// stmt = (Statement) conn.createStatement();
					queryEnds = checkStatementEnds(line);
					query.append(line);
					if (queryEnds) {
						// res=query.toString();
						stmt.executeUpdate(query.toString().replace("[;]", ""));
						query.setLength(0);

					}
				} catch (SQLException e) {
					System.err.println("Message: " + e.getMessage());
					System.err.println("SQLState: " + e.getSQLState());
					System.err.println("ErrorCode: " + e.getErrorCode());
				}
			}
			

			try {
				if (stmt != null) {
					stmt.close();
					ConnectionManager.getInstance().checkIn(conn);

					// conn.close();
				}
			} catch (SQLException e) {
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private boolean isComment(String line) {
		if ((line != null) && (line.length() > 0))
			return (line.charAt(0) == '#' || line.charAt(0) == '-' || line
					.charAt(0) == '�');

		return false;
	}

	private boolean checkStatementEnds(String s) {
		return (s.indexOf(QUERY_ENDS) != -1);
	}

	// creamos el esquema de la base de datos

	public void ejecSchema(String squema) {
		// Statement stmt = null;
		ResultSet result = null;
		Statement stmt = null;

		try {
			// stmt = (Statement) conn.createStatement();
			try {
				stmt = (Statement) conn.createStatement();
			} catch (NullPointerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			// stmt = (Statement) conn.prepareStatement("CREATE DATABASE IF NOT
			// EXISTS " + squema);//conn.createStatement();
			// if (squema!=""){
			stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + squema);
			// Para ver el sist op y ejecutar desde lineas de comandos
			// Properties prop = new Properties();
			// String sistemaOp=prop.getProperty("os.name");
			// if(sistemaOp.length()>=7){
			// sistemaOp=sistemaOp.substring(0,7);
			// }
			// if(!sistemaOp.equals("Windows")){
			// String lineaComando="mysql -h localhost -u root -p 'practica'";
			// String sql=CREATE DATABASE IF NOT EXISTS "+squema+";"
			// Runtime.getRuntime().exec(lineaComando);
			// Runtime.getRuntime().exec(sql);
			// }else{

		} catch (SQLException e) {
			System.err.println("Message: " + e.getMessage());
			System.err.println("SQLState: " + e.getSQLState());
			System.err.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					ConnectionManager.getInstance().checkIn(conn);
				}
			} catch (SQLException e) {
			}
		}

	}
}